﻿using System.Text;

namespace Miao.ML
{
	public class StringData : WinMLData, INullable
	{
		private static readonly StringBuilder stringBuilder = new StringBuilder(128);

		public bool isNull => value == null;

		public string value { get; set; }

		public sealed override DataType type => DataType.String;

		public static string ToString(object value)
		{
			if (value == null)
			{
				return "null";
			}
			stringBuilder.Append(Keyword.doubleQuotes);
			string text = value.ToString();
			for (int i = 0; i < text.Length; i++)
			{
				switch (text[i])
				{
				case '\r':
					stringBuilder.Append('\\');
					stringBuilder.Append('r');
					break;
				case '\n':
					stringBuilder.Append('\\');
					stringBuilder.Append('n');
					break;
				case '\\':
					stringBuilder.Append('\\');
					stringBuilder.Append('\\');
					break;
				case Keyword.doubleQuotes:
					stringBuilder.Append('\\');
					stringBuilder.Append(Keyword.doubleQuotes);
					break;
				default:
					stringBuilder.Append(text[i]);
					break;
				}
			}
			stringBuilder.Append(Keyword.doubleQuotes);
			string result = stringBuilder.ToString();
			stringBuilder.Length = 0;
			return result;
		}

		public StringData()
		{
		}

		public StringData(string value)
		{
			this.value = value;
		}

		public override void SetValueByText(string text)
		{
			value = text;
		}

		public override string ToString()
		{
			return ToString(value);
		}
	}
}
